<?php

namespace App\Console\Commands;

use App\Models\Family;
use App\Models\Staff;
use Illuminate\Console\Command;

class CalcAgeByID extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'calc:age';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'calc age by id card number of staff or staff family';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $families = Family::query()->whereNotNull('id_card')->get(['id','id_card','age']);
        foreach ($families as $family){

            $family->age=$this->getAgeByID($family->id_card);
            $family->save();
        }
        $this->info('families age calc finished');
        $staffs = Staff::query()->whereNotNull('id_card')->get(['id','id_card','age']);
        foreach ($staffs as $staff){
            $staff->age = $this->getAgeByID($staff->id_card);
            $staff->save();
        }
        $this->info('staff age calc finished');
    }

    public function getAgeByID($id)
    {

        //过了这年的生日才算多了1周岁
        if (empty($id)) return null;
        $birthday = substr($id, 6, 8);
        if(is_numeric($birthday)){
            $date = strtotime(substr($id, 6, 8));
            //获得出生年月日的时间戳
            $today = strtotime('today');
            //获得今日的时间戳 111cn.net
            $diff = floor(($today - $date) / 86400 / 365);
            //得到两个日期相差的大体年数

            //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
            $age = strtotime(substr($id, 6, 8) . ' +' . $diff . 'years') > $today ? ($diff + 1) : $diff;
            if($age<256){
                return $age;
            }else{
                return null;
            }


        }else{
            return null;
        }

    }
}
